package com.hkfrich.generator.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkfrich.common.constant.Constants;
import com.hkfrich.common.exception.GenException;
import com.hkfrich.generator.utils.GenUtils;
import com.hkfrich.common.utils.SecurityUtils;
import com.hkfrich.common.utils.StringUtils;
import com.hkfrich.generator.utils.VelocityInitializer;
import com.hkfrich.generator.domain.GenTable;
import com.hkfrich.generator.domain.GenTableColumn;
import com.hkfrich.generator.mapper.GenTableColumnMapper;
import com.hkfrich.generator.mapper.GenTableMapper;
import com.hkfrich.generator.service.GenTableService;
import com.hkfrich.generator.utils.VelocityUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName GenTableServiceImpl
 * @Desscription
 * @Author _HeiShuai
 * @Date 2022/8/27 10:22
 * @Version 1.0
 **/
@Service
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {

    @Resource
    private GenTableMapper genTableMapper;

    @Resource
    private GenTableColumnMapper genTableColumnMapper;


    @Override
    public Page<GenTable> selectDbTableList(Page<GenTable> page, GenTable genTable) {
        return genTableMapper.selectDbTableList(page,genTable);
    }

    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames) {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    @Override
    @Transactional //事务
    public void importGenTable(List<GenTable> tableList) {
        Long operUserId = SecurityUtils.getUserId();
        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operUserId);
                int row = genTableMapper.insertGenTable(table);
                if (row > 0)
                {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        genTableColumnMapper.insert(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new GenException("导入失败：" + e.getMessage());
        }
    }

    @Override
    public byte[] createGenTableFile(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            creatorGenTableCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    @Override
    public boolean removeOneGenTableAndGenTableColumns(List<Long> list) {
        LambdaQueryWrapper<GenTableColumn> query = new LambdaQueryWrapper<>();
        query.in(GenTableColumn::getTableId,list);
        return genTableColumnMapper.delete(query)>0 && genTableMapper.deleteBatchIds(list)>0;
    }

    @Override
    public Map<String, String> previewCode(Long id) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(id);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    @Override
    public GenTable selectGenTableById(Long id) {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询所有表信息
     *
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll()
    {
        return genTableMapper.selectGenTableAll();
    }

    @Override
    public void validateEdit(GenTable genTable,JSONObject paramsObj) {
        if (Constants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            if (StringUtils.isEmpty(paramsObj.getString(Constants.TREE_CODE)))
            {
                throw new RuntimeException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(Constants.TREE_PARENT_CODE)))
            {
                throw new RuntimeException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(Constants.TREE_NAME)))
            {
                throw new RuntimeException("树名称字段不能为空");
            }
            else if (Constants.TPL_SUB.equals(genTable.getTplCategory()))
            {
                if (StringUtils.isEmpty(genTable.getSubTableName()))
                {
                    throw new RuntimeException("关联子表的表名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
                {
                    throw new RuntimeException("子表关联的外键名不能为空");
                }
            }
        }
    }

    @Override
    public void updateGenTable(GenTable genTable, JSONObject paramsObj) {
        String options = JSON.toJSONString(paramsObj);
        genTable.setOptions(options);
        int row = genTableMapper.updateById(genTable);
        if (row > 0)
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                genTableColumnMapper.updateById(cenTableColumn);
            }
        }
    }

    @Override
    @Transactional
    public void synchDb(String tableName)
    {
        GenTable table = genTableMapper.selectGenTableInfoByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new GenException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtils.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnMapper.updateById(column);
            }
            else
            {
                genTableColumnMapper.insert(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            genTableColumnMapper.deleteBatchIds(delColumns);
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable)
    {
        JSONObject paramsObj = JSON.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj))
        {
            String treeCode = paramsObj.getString(Constants.TREE_CODE);
            String treeParentCode = paramsObj.getString(Constants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(Constants.TREE_NAME);
            String parentMenuId = paramsObj.getString(Constants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(Constants.PARENT_MENU_NAME);
            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }
    /**
     * 查询表信息并生成代码
     */
    private void creatorGenTableCode(String tableName, ZipOutputStream zip){
        // 查询表信息
//        LambdaQueryWrapper<GenTable> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(GenTable::getTableName,tableName);
//        GenTable table = genTableMapper.selectOne(wrapper);
        GenTable table = genTableMapper.selectGenTableInfoByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(table);
//         获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
//                 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            }
            catch (Exception e)
            {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table)
    {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotEmpty(subTableName))
        {
            LambdaQueryWrapper<GenTable> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GenTable::getTableName,subTableName);
            table.setSubTable(genTableMapper.selectOne(wrapper));
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table){
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (Constants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

}
